package storage.v1;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class StorageWithRegistry extends AbstractStorageWithRegistry<String> {
	
	
	public StorageWithRegistry(String registerPath, String prefix) {
		super(registerPath, prefix);
	}

	@Override
	protected String readFromFile( File f ) {

		String content = readUTFContent( f ) ;
		if( content == null )
			return null ;
		
		final int i = content.indexOf( LABLE_SEPARATOR );
		if( i < 0 )
			return null ;
		
		int start = i + LABLE_SEPARATOR.length() ;
		String text = content.substring(start) ;
			
		return text ;
	}
	
	private final static String LABLE_SEPARATOR = "\n\n<<<>>>\n\n" ; 
	
	@Override
	protected void writeToFile( File f, String content, String label ){
		
		try {
			FileOutputStream fos = new FileOutputStream(f);
			DataOutputStream dos = new DataOutputStream( fos ) ;
			
			StringBuilder sb = new StringBuilder() ;
			sb.append(label) ;
			sb.append( LABLE_SEPARATOR ) ;			
			sb.append(content) ;
			
			byte[] byteContent = sb.toString().getBytes("UTF-8") ;
			
			dos.write(byteContent);
			dos.close() ;
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}
	
	

}
